import React, { Component } from 'react'
import { NavBar,Toast } from 'antd-mobile';
import './index.less';
import { List,Button } from 'antd-mobile';
import axios from 'axios';

const Item = List.Item;
export default class UserCenter extends Component {
    state = {
        user: {}
    }
    //组件渲染
    render() {
        return (
            <div className="user-center">
                <NavBar mode="light" >个人中心</NavBar>
                <div className="gap-50"></div>
                {/* 个人头像和欢迎 start */}
                <div className="profile">
                    <img src='/images/xiaohigh.webp' alt="" />
                    <p>欢迎用户: {this.state.user.username}</p>
                </div>
                {/* 个人头像和欢迎 end */}
                <div className="gap-20"></div>
                <div className="gap-10"></div>
                {/* 个人信息 start */}
                <List className="my-list">
                    <Item extra={this.state.user.nickName}>昵称</Item>
                    <Item extra={this.state.user.phone}>手机号</Item>
                </List>
                {/* 个人信息 end */}
                <div className="gap-50"></div>
                <Button type="warning" onClick={this.logout}>退出登录</Button>
            </div>
        )
    }

    //组件挂载完毕
    async componentDidMount(){
        let result = await axios({
            method: 'post',
            url: '/login/verify'
        });
        //判断用户是否登录
        if(result.data.code !== 20000){
            Toast.fail('您还没有请先登录');
            //跳转
            this.props.history.push('/login');
        }else{
            this.setState({
                user: result.data.data
            })
        }
    }

    logout = async () => {
        console.log(this.state.user._id);
        //发送 AJAX 请求
        let result = await axios.post('/logout', {_id: this.state.user._id});
        //判断结果
        if(result.data.code !== 20000){
            Toast.fail('退出失败!');
        }else{
            Toast.success('成功退出');
            //跳转
            this.props.history.replace('/login');
        }
    }
}
